<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useBookStore } from '@/stores/book';
import { useRedisStore } from '@/stores/redis';
import { 
  User, 
  Reading, 
  Coin, 
  CaretTop, 
  CaretBottom, 
  Minus, 
  Operation, 
  Refresh, 
  ArrowRight, 
  Monitor 
} from '@element-plus/icons-vue';

const router = useRouter();
const bookStore = useBookStore();
const redisStore = useRedisStore();
const userStore = useUserStore();

const bookCount = ref(0);
const redisStatus = ref('未连接');
const loading = ref(true);
const currentUser = ref('');
const currentEnv = ref(import.meta.env.MODE === 'production' ? '生产环境' : '开发环境');
const systemInfo = ref({
  javaVersion: 'JDK 17',
  springBootVersion: '3.x',
  serverTime: new Date().toLocaleString()
});

const redisInfo = ref({
  mode: 'standalone',
  version: '未知',
  memory: '128MB',
  connections: 5
});

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 获取图书数量
    const bookData = await bookStore.fetchBooks(1, 1);
    bookCount.value = bookData.count || 0;
    
    // 获取Redis状态
    try {
      const redisInfoData = await redisStore.fetchRedisInfo();
      console.log('Redis信息API返回:', redisInfoData);
      
      redisStatus.value = redisInfoData && redisInfoData.status === 'connected' ? '已连接' : '未连接';
      if (redisInfoData) {
        // 兼容集群和单机模式的数据处理
        const isCluster = redisInfoData.mode && (
          redisInfoData.mode.includes('集群') || 
          redisInfoData.mode.toLowerCase().includes('cluster')
        );
        
        redisInfo.value = {
          mode: redisInfoData.mode || 'standalone',
          version: getRedisVersion(redisInfoData, isCluster),
          memory: getRedisMemory(redisInfoData, isCluster),
          connections: redisInfoData.connections || 0,
          isCluster: isCluster
        };
        
        console.log(`Redis模式: ${isCluster ? '集群模式' : '单机模式'}`, redisInfo.value);
      }
    } catch (error) {
      redisStatus.value = '连接失败';
      console.error('Redis连接失败:', error);
    }
  } catch (error) {
    console.error('加载数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 跳转到图书管理
const goToBooks = () => {
  router.push('/books');
};

// 跳转到Redis管理
const goToRedis = () => {
  router.push('/redis');
};

// 跳转到个人资料
const goToProfile = () => {
  router.push('/profile');
};

// 处理用户登出
const handleLogout = async () => {
  try {
    await userStore.logout();
    router.push('/login');
  } catch (error) {
    console.error('登出失败:', error);
  }
};

// 获取Redis版本信息 - 兼容集群和单机模式
const getRedisVersion = (redisData, isCluster) => {
  if (redisData.version && redisData.version !== '未知') {
    return redisData.version;
  }
  
  // 根据模式返回不同的默认版本提示
  if (isCluster) {
    return redisData.clusterVersion || '7.0+ 集群';
  } else {
    return redisData.standaloneVersion || '7.0+ 单机';
  }
};

// 获取Redis内存信息 - 兼容集群和单机模式  
const getRedisMemory = (redisData, isCluster) => {
  if (redisData.memory && redisData.memory !== '未知') {
    return redisData.memory;
  }
  
  // 集群模式可能有多个节点的内存信息
  if (isCluster) {
    return redisData.totalMemory || redisData.clusterMemory || '集群总内存';
  } else {
    return redisData.usedMemory || '128MB';
  }
};

onMounted(async () => {
  // 初始化用户信息
  await userStore.initUserInfo();
  
  // 检查是否有有效的token
  const token = localStorage.getItem('token');
  const tokenExpiration = localStorage.getItem('tokenExpiration');
  console.log('Dashboard检查token:', token ? '存在' : '不存在');
  console.log('Dashboard检查过期时间:', tokenExpiration);
  console.log('Dashboard当前时间:', Date.now());
  
  if (!token) {
    console.warn('未找到token，跳转登录页');
    router.push('/login');
    return;
  }
  
  // 检查token是否过期
  if (userStore.isTokenExpired()) {
    console.warn('token已过期，跳转登录页');
    router.push('/login');
    return;
  }
  
  // 设置当前用户
  currentUser.value = userStore.getCurrentUsername();
  
  // 输出环境信息到控制台
  console.log(
    `%cNODE_ENV:%c ${import.meta.env.MODE}`,
    'color: #409EFF; font-weight: bold;',
    'color: #67C23A; font-weight: bold;'
  );
  console.log(
    `%cAPI Base URL:%c ${import.meta.env.VITE_APP_BASE_API}`,
    'color: #409EFF; font-weight: bold;',
    'color: #67C23A; font-weight: bold;'
  );
  
  loadData();
  
  // 每60秒更新一次系统时间
  setInterval(() => {
    systemInfo.value.serverTime = new Date().toLocaleString();
  }, 60000);
});
</script>

<template>
  <div class="dashboard-container">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <div class="welcome-text">
          <h1>系统管理仪表盘</h1>
          <p>今天是 {{ new Date().toLocaleDateString() }},祝您工作愉快</p>
        </div>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <el-row :gutter="24" class="stats-section">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card users-card">
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">1</div>
            <div class="stat-label">在线用户</div>
            <div class="stat-trend">
              <el-icon class="trend-stable"><Minus /></el-icon>
              <span>稳定</span>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card books-card">
          <div class="stat-icon">
            <el-icon><Reading /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ bookCount }}</div>
            <div class="stat-label">图书总数</div>
            <div class="stat-trend">
              <el-icon class="trend-up"><CaretTop /></el-icon>
              <span>+12%</span>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card redis-card">
          <div class="stat-icon">
            <el-icon><Coin /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ redisStatus }}</div>
            <div class="stat-label">Redis状态</div>
            <div class="stat-trend">
              <el-icon :class="redisStatus === '已连接' ? 'trend-up' : 'trend-down'">
                <CaretTop v-if="redisStatus === '已连接'" />
                <CaretBottom v-else />
              </el-icon>
              <span>{{ redisStatus === '已连接' ? '连接正常' : '连接异常' }}</span>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card database-card">
          <div class="stat-icon">
            <el-icon><Coin /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">已连接</div>
            <div class="stat-label">数据库状态</div>
            <div class="stat-trend">
              <el-icon class="trend-up"><CaretTop /></el-icon>
              <span>连接正常</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要功能区域 -->
    <el-row :gutter="24" class="main-section">
      <el-col :span="24">
        <el-card class="feature-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3><el-icon><Operation /></el-icon> 快速操作</h3>
              <el-button type="text" @click="loadData">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="quick-actions-grid-full">
            <div class="action-item" @click="goToBooks">
              <div class="action-icon books-action">
                <el-icon><Reading /></el-icon>
              </div>
              <div class="action-content">
                <h4>图书管理</h4>
                <p>管理图书信息，增删改查</p>
              </div>
              <el-icon class="action-arrow"><ArrowRight /></el-icon>
            </div>
            
            <div class="action-item" @click="goToRedis">
              <div class="action-icon redis-action">
                <el-icon><Coin /></el-icon>
              </div>
              <div class="action-content">
                <h4>Redis管理</h4>
                <p>缓存管理，性能监控</p>
              </div>
              <el-icon class="action-arrow"><ArrowRight /></el-icon>
            </div>
            
            
            <div class="action-item" @click="goToProfile">
              <div class="action-icon profile-action">
                <el-icon><User /></el-icon>
              </div>
              <div class="action-content">
                <h4>个人资料</h4>
                <p>查看和编辑个人信息</p>
              </div>
              <el-icon class="action-arrow"><ArrowRight /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>


    <!-- 系统信息 -->
    <el-row :gutter="24" class="system-section">
      <el-col :span="24">
        <el-card class="system-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3><el-icon><Monitor /></el-icon> 技术栈 & 运行环境</h3>
              <el-tag type="success" size="small">运行正常</el-tag>
            </div>
          </template>
          <div class="system-grid">
            <div class="system-item">
              <div class="system-label">后端框架</div>
              <div class="system-value">Spring Boot 3.x</div>
            </div>
            <div class="system-item">
              <div class="system-label">前端框架</div>
              <div class="system-value">Vue 3.x</div>
            </div>
            <div class="system-item">
              <div class="system-label">数据库</div>
              <div class="system-value">MySQL 8.0</div>
            </div>
            <div class="system-item">
              <div class="system-label">缓存服务</div>
              <div class="system-value">Redis {{ redisInfo.version || '7.0.0' }}</div>
            </div>
            <div class="system-item">
              <div class="system-label">部署环境</div>
              <div class="system-value">{{ currentEnv }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 24px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

/* 欢迎横幅样式 */
.welcome-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h1 {
  font-size: 32px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.welcome-text p {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.weather-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.1);
  padding: 12px 16px;
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.weather-icon {
  font-size: 20px;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 16px;
  height: 120px;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.books-card .stat-icon {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.users-card .stat-icon {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.redis-card .stat-icon {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.database-card .stat-icon {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.system-card .stat-icon {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #1a202c;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #718096;
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.trend-up {
  color: #48bb78;
}

.trend-down {
  color: #f56565;
}

.trend-stable {
  color: #ed8936;
}

/* 主要功能区域样式 */
.main-section {
  margin-bottom: 24px;
}

.feature-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-header h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  padding: 8px 0;
}

.quick-actions-grid-full {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 8px 0;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  border-radius: 12px;
  background: #f7fafc;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid transparent;
}

.action-item:hover {
  background: #edf2f7;
  border-color: #e2e8f0;
  transform: translateY(-2px);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.books-action {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.redis-action {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.demo-action {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.profile-action {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.action-content h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a202c;
}

.action-content p {
  margin: 0;
  font-size: 14px;
  color: #718096;
}

.action-arrow {
  margin-left: auto;
  color: #a0aec0;
  transition: all 0.3s ease;
}

.action-item:hover .action-arrow {
  color: #667eea;
  transform: translateX(4px);
}

/* 用户资料卡片样式 */
.profile-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.profile-content {
  text-align: center;
  padding: 8px 0;
}

.profile-avatar {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.online-status {
  position: absolute;
  bottom: 8px;
  right: 8px;
  width: 16px;
  height: 16px;
  background: #48bb78;
  border: 3px solid white;
  border-radius: 50%;
}

.profile-info h3 {
  margin: 0 0 12px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
}

.profile-tags {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-bottom: 16px;
}

.profile-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
  padding: 16px 0;
  background: #f7fafc;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.stat-name {
  font-size: 12px;
  color: #718096;
}

.profile-btn {
  width: 100%;
  border-radius: 8px;
}

/* 系统信息样式 */
.system-section {
  margin-bottom: 24px;
}

.system-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
}

.system-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
  padding: 8px 0;
}

.system-item {
  text-align: center;
  padding: 16px;
  background: #f7fafc;
  border-radius: 8px;
}

.system-label {
  font-size: 14px;
  color: #718096;
  margin-bottom: 8px;
}

.system-value {
  font-size: 16px;
  font-weight: 600;
  color: #1a202c;
}

/* 用户信息水平布局样式 */
.profile-section {
  margin-bottom: 24px;
}

.profile-content-horizontal {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 8px 0;
}

.profile-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.profile-basic h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.profile-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.profile-stats-horizontal {
  display: flex;
  gap: 32px;
}

.profile-btn-horizontal {
  border-radius: 8px;
}

.profile-actions {
  display: flex;
  gap: 12px;
}

/* 连接状态颜色统一 */
.redis-card .stat-number {
  color: #f56565 !important;
}

.redis-card.connected .stat-number,
.database-card .stat-number {
  color: #48bb78 !important;
}

/* 响应式设计 */
/* 平板适配 */
@media (max-width: 1024px) {
  .dashboard-container {
    padding: 20px;
  }
  
  .quick-actions-grid-full {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .system-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
}

/* 手机适配 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }
  
  .banner-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    padding: 20px 16px;
  }
  
  .welcome-text h1 {
    font-size: 24px;
    line-height: 1.3;
  }
  
  .welcome-text p {
    font-size: 14px;
  }
  
  .quick-actions-grid, .quick-actions-grid-full {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .action-item {
    padding: 16px;
    gap: 12px;
  }
  
  .action-icon {
    width: 40px;
    height: 40px;
  }
  
  .action-content h3 {
    font-size: 16px;
  }
  
  .action-content p {
    font-size: 13px;
  }
  
  .system-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .system-item {
    padding: 16px;
    text-align: center;
  }
  
  .system-label {
    font-size: 12px;
  }
  
  .system-value {
    font-size: 14px;
  }
  
  .profile-content-horizontal {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .profile-right {
    flex-direction: column;
    gap: 16px;
  }
  
  .profile-stats-horizontal {
    justify-content: center;
    gap: 20px;
  }
  
  .profile-stat {
    text-align: center;
  }
  
  .profile-stat-value {
    font-size: 18px;
  }
  
  .profile-stat-label {
    font-size: 12px;
  }
  
  .el-card {
    margin-bottom: 16px;
  }
  
  .stat-trend .el-icon {
    font-size: 12px;
  }
  
  .main-section,
  .profile-section,
  .system-section {
    margin-top: 12px;
  }
  
  .card-header h3 {
    font-size: 16px;
  }
  
  .quick-actions-grid-full {
    gap: 8px;
  }
  
  .action-item {
    padding: 12px;
  }
  
  .action-content h4 {
    font-size: 14px;
    margin-bottom: 4px;
  }
  
  .action-content p {
    font-size: 12px;
  }
}

/* 小屏手机适配 */
@media (max-width: 480px) {
  .dashboard-container {
    padding: 12px;
  }
  
  .banner-content {
    padding: 16px 12px;
  }
  
  .welcome-text h1 {
    font-size: 20px;
  }
  
  .system-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .system-item {
    padding: 12px;
  }
  
  .action-item {
    padding: 12px;
  }
  
  .profile-stats-horizontal {
    gap: 16px;
  }
  
  .profile-stat-value {
    font-size: 16px;
  }
  
  .el-card__body {
    padding: 12px;
  }
}
</style>
